﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using DevExpress.XtraEditors;
using System.Data.SqlClient;

namespace TCCT_CTC_CSDLDangVienV1.DanhMuc
{
    public partial class frmDauMoiList : frmBase
    {
        private string Action = MyConst.ACTION.Insert;
        public string SelectedID = string.Empty;
        private bool IsFormFind = false;

        public frmDauMoiList()
        {
            InitializeComponent();
        }

       
        private static frmDauMoiList _instanceFind = null;

        public static frmDauMoiList InstanceFind
        {
            get
            {
                if (_instanceFind == null || _instanceFind.IsDisposed)
                    _instanceFind = new frmDauMoiList();

                _instanceFind.IsFormFind = true;

                return _instanceFind;
            }
            set { _instanceFind = value; }
        }

        private void frmDauMoiList_Load(object sender, EventArgs e)
        {
            try
            {
                ApplyUI();

                if (!MyCommon.CurrentUserIsAdministrator && !IsFormFind)
                {
                    MyCommon.ShowMessage("Bạn không có quyền truy cập mục này. \nVui lòng liên hệ với người quản trị hệ thống");
                    this.Enabled = false;
                    return;
                }
                else if (!MyCommon.CurrentUserIsAdministrator && IsFormFind)
                {
                    gCapNhatThongTin.Visible = false;
                    menuStrip1.Enabled = false;
                }

                BindDataToControl();

                BindDataToGrid();

            }
            catch (Exception _ex)
            {
                ShowErrorMessage(_ex);
            }
        }

        //Nơi gán thuộc tính giao diện cho các control
        private void ApplyUI()
        {
            UI.Button.ApplyInsert(btnThemMoi);
            UI.Button.ApplyInsert(btnThemVaoNodeHienTai);
            UI.Button.ApplyUpdate(btnSuaDoi);
            UI.Button.ApplyUpdate(btnTaiLai);

            UI.Button.ApplyDelete(btnXoaBo);
            UI.Button.ApplyClose(btnThoat);
            UI.Button.ApplyAccept(btnChapNhan);
            UI.Button.ApplyExportExcel(btnXuatExcel);

            if (!IsFormFind) btnChapNhan.Visible = false;
            else
            {
                gCapNhatThongTin.Enabled = false;
                gCapNhatThongTin.Visible = false;
            }

            UI.TextBox.ApplyFind(txtTenGoiFind);


            this.dgData.Columns["CreateDate"].Format.FormatType = DevExpress.Utils.FormatType.DateTime;
            this.dgData.Columns["CreateDate"].Format.FormatString = MyConst.FORMAT_DATETIME.ddMMyyyyHHmmss;

            this.dgData.Columns["UpdateDate"].Format.FormatType = DevExpress.Utils.FormatType.DateTime;
            this.dgData.Columns["UpdateDate"].Format.FormatString = MyConst.FORMAT_DATETIME.ddMMyyyyHHmmss;


        }


        //Nơi tải dữ liệu danh mục lên các control để lựa chọn: ví dụ: Combobox, listbox ...
        private void BindDataToControl()
        {
        }

        //Nơi tải dữ liệu lên grid chứa dữ liệu
        private void BindDataToGrid()
        {
            try
            {
                DataTable temdt = SqlHelper.ExecuteDataTable(CommandType.Text, "Select * from tblDauMoi Where ID='" + MyCommon.CurrentUserDauMoiID + "' ");


                string sql = "select DM.*, (Select Top 1 IsNull(HoTen,'') As HoTen From tblUser U1 Where ID=DM.UserID And DauMoiID=DM.ID) As CapNhatCuoi, CapTren, DM.CreateDate, DM.UpdateDate " +
                          "From tblDauMoi DM Where  (DM.CapTren Like '%" + temdt.Rows[0]["CapTren"].ToString() + "%' OR DM.CapTren IS NULL) ";
                if (!chkTatCa.Checked) sql += " And Deleted<>1  ";
                dgData.DataSource = SqlHelper.ExecuteDataTable(CommandType.Text, sql);
                dgData.ExpandAll();
            }
            catch (Exception _ex)
            {
                ShowErrorMessage(_ex);
            }
        }

        private void btnThemMoi_Click(object sender, EventArgs e)
        {
            SqlTransaction MyTran = SqlHelper.BeginTransaction();
            try
            {
                DanhMuc.frmDauMoiUpdate ff = new frmDauMoiUpdate();
                ff.Action = MyConst.ACTION.Insert;
                bool MyTranCommited = false;
                if (ff.ShowDialog() == DialogResult.OK)
                {
                    string sql = "Insert Into tblDauMoi(MaDV, TenDV, TenCSD, Ky_Hieu, DauMoi, Begin_ID, End_ID, UserID, DauMoi_ID, CreateDate) Values(@MaDV, @TenDV, @TenCSD, @Ky_Hieu, @DauMoi, @Begin_ID, @End_ID, @UserID, @DauMoi_ID, GetDate()); ";
                    sql += "Select Max(ID) From tblDau_Moi ";
                    List<SqlParameter> arrParameters = new List<SqlParameter>();

                    arrParameters.Add(SqlHelper.CreateParameterObject("@MaDV", SqlDbType.NVarChar, ParameterDirection.Input, ff.txtMaDV.Text.Trim()));
                    arrParameters.Add(SqlHelper.CreateParameterObject("@TenDV", SqlDbType.NVarChar, ParameterDirection.Input, ff.txtTenDV.Text.Trim()));
                    arrParameters.Add(SqlHelper.CreateParameterObject("@TenCSD", SqlDbType.NVarChar, ParameterDirection.Input, ff.txtViet_Tat.Text.Trim()));
                    arrParameters.Add(SqlHelper.CreateParameterObject("@Ky_Hieu", SqlDbType.NVarChar, ParameterDirection.Input, ff.txtKy_Hieu.Text.Trim()));
                    arrParameters.Add(SqlHelper.CreateParameterObject("@Begin_ID", SqlDbType.NVarChar, ParameterDirection.Input, ff.txtSoCB.Text.Trim()));
                    arrParameters.Add(SqlHelper.CreateParameterObject("@End_ID", SqlDbType.NVarChar, ParameterDirection.Input, ff.txtLoai.Text.Trim()));

                    arrParameters.Add(SqlHelper.CreateParameterObject("@UserID", SqlDbType.Int, ParameterDirection.Input, MyCommon.CurrentUserID));
                    arrParameters.Add(SqlHelper.CreateParameterObject("@DauMoi_ID", SqlDbType.Int, ParameterDirection.Input, MyCommon.CurrentUserDauMoiID));
                    int maxID = Util.ToInt(SqlHelper.ExecuteScalar(MyTran, CommandType.Text, sql, arrParameters));

                    sql = "Update tblDau_Moi Set CapTren=@CapTren Where ID=@ID ";
                    arrParameters = new List<SqlParameter>();

                    arrParameters.Add(SqlHelper.CreateParameterObject("@CapTren", SqlDbType.NVarChar, ParameterDirection.Input, ";" + maxID + ";"));
                    arrParameters.Add(SqlHelper.CreateParameterObject("@ID", SqlDbType.Int, ParameterDirection.Input, maxID));

                    SqlHelper.ExecuteNonQuery(MyTran, CommandType.Text, sql, arrParameters);
                    MyTran.Commit();
                    MyTranCommited = true;
                    BindDataToGrid();

                }
                if (!MyTranCommited)
                    MyTran.Commit();
            }
            catch (Exception _ex)
            {
                MyTran.Rollback();
                ShowErrorMessage(_ex);
            }
        }

        private void btnSuaDoi_Click(object sender, EventArgs e)
        {
            SqlTransaction MyTran = SqlHelper.BeginTransaction();
            try
            {
                DanhMuc.frmDauMoiUpdate ff = new frmDauMoiUpdate();
                ff.Action = MyConst.ACTION.Update;
                bool MyTranCommited = false;
                if (ff.ShowDialog() == DialogResult.OK)
                {
                    string sql = "Update tblDau_Moi Set MaDV=@MaDV, TenDV=@TenDV, Viet_Tat=@Viet_Tat, Ky_Hieu=@Ky_Hieu, DauMoi=@DauMoi, Begin_ID=@Begin_ID, End_ID=@End_ID, UserID=@UserID, DauMoi_ID=@DauMoi_ID, UpdateDate=GetDate() Where ID=@ID; ";
                    List<SqlParameter> arrParameters = new List<SqlParameter>();

                    arrParameters.Add(SqlHelper.CreateParameterObject("@MaDV", SqlDbType.NVarChar, ParameterDirection.Input, ff.txtMaDV.Text.Trim()));
                    arrParameters.Add(SqlHelper.CreateParameterObject("@TenDV", SqlDbType.NVarChar, ParameterDirection.Input, ff.txtTenDV.Text.Trim()));
                    arrParameters.Add(SqlHelper.CreateParameterObject("@Viet_Tat", SqlDbType.NVarChar, ParameterDirection.Input, ff.txtViet_Tat.Text.Trim()));
                    arrParameters.Add(SqlHelper.CreateParameterObject("@Ky_Hieu", SqlDbType.NVarChar, ParameterDirection.Input, ff.txtKy_Hieu.Text.Trim()));
                    arrParameters.Add(SqlHelper.CreateParameterObject("@Begin_ID", SqlDbType.NVarChar, ParameterDirection.Input, ff.txtSoCB.Text.Trim()));
                    arrParameters.Add(SqlHelper.CreateParameterObject("@End_ID", SqlDbType.NVarChar, ParameterDirection.Input, ff.txtLoai.Text.Trim()));
                    arrParameters.Add(SqlHelper.CreateParameterObject("@UserID", SqlDbType.Int, ParameterDirection.Input, MyCommon.CurrentUserID));
                    arrParameters.Add(SqlHelper.CreateParameterObject("@DauMoi_ID", SqlDbType.Int, ParameterDirection.Input, MyCommon.CurrentUserDauMoiID));

                    arrParameters.Add(SqlHelper.CreateParameterObject("@ID", SqlDbType.Int, ParameterDirection.Input, dgData.FocusedNode.GetValue("ID").ToString()));

                    SqlHelper.ExecuteNonQuery(MyTran, CommandType.Text, sql, arrParameters);
                    MyTran.Commit();
                    MyTranCommited = true;
                    BindDataToGrid();

                }
                if (!MyTranCommited)
                    MyTran.Commit();
            }
            catch (Exception _ex)
            {
                MyTran.Rollback();
                ShowErrorMessage(_ex);
            }
        }

        private bool IsInvalid()
        {
            bool isValid = true;
            ValidationMessage = null;
            AppendValidationMessage("Bạn cần nhập dữ liệu cho: ");
            //if (txtTenGoi.EditValue.ToString().Trim() == "")
            //{
            //    AppendValidationMessage("Tên gọi");
            //    isValid = false;
            //}
            //Hiện thông báo lỗi khi isValid=false
            if (!isValid)
                ShowValidationMessage();

            return isValid;
        }

        private void btnLuu_Click(object sender, EventArgs e)
        {
            //try
            //{
            //    if (!IsInvalid())
            //        return;

            //    if (Action == MyConst.ACTION.Insert)
            //    {
            //        string sql = "Insert Into tblDau_Moi(TenGoi, CreateDate, UserID, MaDanhMuc) " +
            //            "Values (@TenGoi, GetDate(), @UserID, @MaDanhMuc)";
            //        List<SqlParameter> arrParameters = new List<SqlParameter>();
            //        arrParameters.Add(SqlHelper.CreateParameterObject("@TenGoi", SqlDbType.NVarChar, ParameterDirection.Input, txtTenGoi.Text.Trim()));
            //        arrParameters.Add(SqlHelper.CreateParameterObject("@UserID", SqlDbType.BigInt, ParameterDirection.Input, Common.CurrentUserID));
            //        arrParameters.Add(SqlHelper.CreateParameterObject("@MaDanhMuc", SqlDbType.NVarChar, ParameterDirection.Input, MaDanhMuc));
            //        SqlHelper.ExecuteNonQuery(CommandType.Text, sql, arrParameters);

            //    }
            //    else
            //    {
            //        string sql = "Update tblDau_Moi Set TenGoi=@TenGoi, UpdateDate=GetDate(), UserID=@UserID " +
            //           "Where ID=@ID ";
            //        List<SqlParameter> arrParameters = new List<SqlParameter>();
            //        arrParameters.Add(SqlHelper.CreateParameterObject("@TenGoi", SqlDbType.NVarChar, ParameterDirection.Input, txtTenGoi.Text.Trim()));
            //        arrParameters.Add(SqlHelper.CreateParameterObject("@ID", SqlDbType.BigInt, ParameterDirection.Input, SelectedID));
            //        arrParameters.Add(SqlHelper.CreateParameterObject("@UserID", SqlDbType.BigInt, ParameterDirection.Input, Common.CurrentUserID));
            //        SqlHelper.ExecuteNonQuery(CommandType.Text, sql, arrParameters);

            //    }

            //    BindDataToGrid();

            //    ResetValues(gCapNhatThongTin);

            //    Action = MyConst.ACTION.Insert;
            //    Common.ShowMessage("Lưu dữ liệu thành công");
            //}
            //catch (Exception _ex)
            //{
            //    ShowErrorMessage(_ex);
            //}
        }


        private void btnThoat_Click(object sender, EventArgs e)
        {
            try
            {
                this.DialogResult = DialogResult.Cancel;
                this.Close();
            }
            catch (Exception _ex)
            {
                ShowErrorMessage(_ex);
            }
        }

        private void txtTenGoiFind_EditValueChanged(object sender, EventArgs e)
        {
            try
            {
                ((DataTable)dgData.DataSource).DefaultView.RowFilter = "TenDV Like '%" + txtTenGoiFind.Text.Trim() + "%' ";
            }
            catch (Exception _ex)
            {
                ShowErrorMessage(_ex);
            }
        }

        private void txtTenGoiFind_KeyDown(object sender, KeyEventArgs e)
        {
            try
            {
                if (e.KeyCode == Keys.Down)
                    dgData.Focus();
            }
            catch (Exception _ex)
            {
                ShowErrorMessage(_ex);
            }
        }

        private void btnChapNhan_Click(object sender, EventArgs e)
        {
            try
            {
                if (dgData.Selection.Count == 0)
                {
                    ShowInfoMessage("Không có kết quả nào được tìm thấy");
                    return;
                }

                if (IsFormFind)
                {
                    this.SelectedID = dgData.FocusedNode.GetValue("ID").ToString();
                    this.DialogResult = DialogResult.OK;
                    this.Close();
                }
            }
            catch (Exception _ex)
            {
                ShowErrorMessage(_ex);
            }
        }

        //Nếu phím là enter và Action=Find thì có nghĩa là chấp nhận kết quả tìm kiếm.
        private void dgData_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                btnChapNhan_Click(null, null);
            }
        }

        private void menuThemMoi_Click(object sender, EventArgs e)
        {
            if (btnThemMoi.Enabled)
                btnThemMoi_Click(null, null);
        }

        private void menuSuaDoi_Click(object sender, EventArgs e)
        {
            if (btnSuaDoi.Enabled)
                btnSuaDoi_Click(null, null);
        }

        private void menuLuu_Click(object sender, EventArgs e)
        {
            if (btnSuaDoi.Enabled)
                btnLuu_Click(null, null);
        }

        private void menuXoaBo_Click(object sender, EventArgs e)
        {
            if (btnXoaBo.Enabled)
                btnXoaBo_Click(null, null);
        }

        private void menuTimKiem_Click(object sender, EventArgs e)
        {
            ResetValues(gTimKiemThongTin);
            txtTenGoiFind.Focus();
        }

        private void menuChapNhan_Click(object sender, EventArgs e)
        {
            btnChapNhan_Click(null, null);
        }

        private void btnXuatExcel_Click(object sender, EventArgs e)
        {
            try
            {
                TreeListExportToExcel(dgData);
            }
            catch (Exception _ex)
            {
                ShowErrorMessage(_ex);
            }
        }

        private void txtTenGoi_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                e.Handled = true;

            }
        }

        private void btnThemVaoNodeHienTai_Click(object sender, EventArgs e)
        {
            if (dgData.FocusedNode == null)
            {
                MyCommon.ShowMessage("Bạn cần chọn một tên danh mục làm cấp trên");
                return;
            }
            SqlTransaction MyTran = SqlHelper.BeginTransaction();
            try
            {
                DanhMuc.frmDauMoiUpdate ff = new frmDauMoiUpdate();
                bool MyTranCommited = false;
                if (ff.ShowDialog() == DialogResult.OK)
                {
                    string sql = "Insert Into tblDau_Moi(ParentID, MaDV, TenDV, Viet_Tat, Ky_Hieu, DauMoi, Begin_ID, End_ID, UserID, DauMoi_ID, CreateDate) Values(@ParentID, @MaDV, @TenDV, @Viet_Tat, @Ky_Hieu, @DauMoi, @Begin_ID, @End_ID, @UserID, @DauMoi_ID, GetDate()); ";
                    sql += "Select Max(ID) From tblDau_Moi ";
                    List<SqlParameter> arrParameters = new List<SqlParameter>();
                    arrParameters.Add(SqlHelper.CreateParameterObject("@ParentID", SqlDbType.Int, ParameterDirection.Input, dgData.FocusedNode.GetValue("ID").ToString()));

                    arrParameters.Add(SqlHelper.CreateParameterObject("@MaDV", SqlDbType.NVarChar, ParameterDirection.Input, ff.txtMaDV.Text.Trim()));
                    arrParameters.Add(SqlHelper.CreateParameterObject("@TenDV", SqlDbType.NVarChar, ParameterDirection.Input, ff.txtTenDV.Text.Trim()));
                    arrParameters.Add(SqlHelper.CreateParameterObject("@Viet_Tat", SqlDbType.NVarChar, ParameterDirection.Input, ff.txtViet_Tat.Text.Trim()));
                    arrParameters.Add(SqlHelper.CreateParameterObject("@Ky_Hieu", SqlDbType.NVarChar, ParameterDirection.Input, ff.txtKy_Hieu.Text.Trim()));
                    arrParameters.Add(SqlHelper.CreateParameterObject("@Begin_ID", SqlDbType.Int, ParameterDirection.Input, Util.ToInt(ff.txtSoCB.Text.Trim())));
                    arrParameters.Add(SqlHelper.CreateParameterObject("@End_ID", SqlDbType.Int, ParameterDirection.Input, Util.ToInt(ff.txtLoai.Text.Trim())));

                    arrParameters.Add(SqlHelper.CreateParameterObject("@UserID", SqlDbType.Int, ParameterDirection.Input, MyCommon.CurrentUserID));
                    arrParameters.Add(SqlHelper.CreateParameterObject("@DauMoi_ID", SqlDbType.Int, ParameterDirection.Input, MyCommon.CurrentUserDauMoiID));
                    int maxID = Util.ToInt(SqlHelper.ExecuteScalar(MyTran, CommandType.Text, sql, arrParameters));

                    sql = "Update tblDau_Moi Set CapTren=@CapTren Where ID=@ID ";
                    arrParameters = new List<SqlParameter>();

                    arrParameters.Add(SqlHelper.CreateParameterObject("@CapTren", SqlDbType.NVarChar, ParameterDirection.Input, dgData.FocusedNode.GetValue("CapTren").ToString() + maxID + ";"));
                    arrParameters.Add(SqlHelper.CreateParameterObject("@ID", SqlDbType.Int, ParameterDirection.Input, maxID));

                    SqlHelper.ExecuteNonQuery(MyTran, CommandType.Text, sql, arrParameters);
                    MyTran.Commit();
                    MyTranCommited = true;
                    BindDataToGrid();

                }
                if (!MyTranCommited)
                    MyTran.Commit();
            }
            catch (Exception _ex)
            {
                MyTran.Rollback();
                ShowErrorMessage(_ex);
            }
        }


        private void btnXoaBo_Click(object sender, EventArgs e)
        {
            if (dgData.FocusedNode.Nodes.Count > 0)
            {
                MyCommon.ShowMessage("Bạn không thể xóa nút này vì còn có nút con cấp dưới. Chỉ có thể xóa khi một nút không có nút con");
                return;
            }

            try
            {
                if (ShowQuestionMessage("Bạn có chắc chắn xóa?") == DialogResult.Yes)
                {
                    string sql = "Update tblDau_Moi Set Deleted=1, UserID=@UserID, UpdateDate=GetDate() Where ID=@ID ";
                    List<SqlParameter> arrParameters = new List<SqlParameter>();


                    arrParameters = new List<SqlParameter>();
                    arrParameters.Add(SqlHelper.CreateParameterObject("@UserID", SqlDbType.Int, ParameterDirection.Input, MyCommon.CurrentUserID));
                    arrParameters.Add(SqlHelper.CreateParameterObject("@ID", SqlDbType.Int, ParameterDirection.Input, dgData.FocusedNode.GetValue("ID").ToString()));

                    SqlHelper.ExecuteNonQuery(CommandType.Text, sql, arrParameters);
                    dgData.Nodes.Remove(dgData.FocusedNode);
                }
            }
            catch (Exception _ex)
            {

                ShowErrorMessage(_ex);
            }
        }

        private void btnTaiLai_Click(object sender, EventArgs e)
        {
            BindDataToGrid();
        }





    }
}